//
//  LCPlayerViewController.m
//  LC
//
//  Created by admin on 17/10/18.
//  Copyright © 2016年 admin. All rights reserved.
//

#import "LCPlayerViewController.h"
#import "JKSongsMessStatus.h"
#import <MediaPlayer/MediaPlayer.h>
#import "LCLrcAnalyzer.h"
#import "LCLrcLine.h"
#import <zhPopupController/zhPopupController.h>
#import "zhWallView.h"
#import "NetworkTool+LCAVPlay.h"
#import "TheHomeManager+Additions.h"
#import "LCSongLyricsTableViewController.h"
#import "LCNavigationController.h"


#import "LSZLyricBookModel.h"

@interface LCPlayerViewController () <UIScrollViewDelegate>

@property (nonatomic,strong) LCSongLyricsTableViewController *songLyricsTableViewController;

@property (weak, nonatomic) IBOutlet UIButton *playOrPauseButton;

@property (weak, nonatomic) IBOutlet UIImageView *backgroundImageView;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
@property (weak, nonatomic) IBOutlet UISlider *bufferProgressSlider;

@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lrcViewLeadingConstraint;

@property (weak, nonatomic) IBOutlet UIButton *randomOrSinglePlayButton;
@property (weak, nonatomic) IBOutlet UILabel *albumLabel;

@property (nonatomic, strong) zhPopupController *zh_popupController; //
@property (nonatomic,strong) NSString * id_id;

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *arrayButtons;//多个 bottm button

@end

@implementation LCPlayerViewController{
    int _playerTime;
}
- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
       self.modalPresentationStyle = UIModalPresentationOverFullScreen;
    }
    return self;
}
- (void)loadView {
    [super loadView];
}
- (void)dealloc{
    NSLog(@"__func__dealloc = %s", __func__);
    if ([self.vcInitDictData[@"PlaybackControl"] isEqualToString:@"YesHidden"]) {
        
    }else{
        [LCFloatingWindow sharedInstance].hidden = NO;
    }
    [self teardownNotifications];
}
- (void)setupPan {
    // 添加手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [self.view addGestureRecognizer:pan];
    self.view.layer.anchorPoint = CGPointMake(0.5, 1.5);
}
#pragma mark
#pragma mark - pan 手势
- (void)pan:(UIPanGestureRecognizer *)pan {
    
    // 1. 获取移动的距离
    CGPoint movePoint = [pan translationInView:pan.view];
    
    // 2. 计算比例
    CGFloat angle = (movePoint.x * M_PI_2) / self.view.frame.size.width;
    
    // 3. 让view进行位移
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
        case UIGestureRecognizerStateChanged:
            
        {
            self.view.transform = CGAffineTransformMakeRotation(angle);
        }
            break;
            
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateFailed:
        case UIGestureRecognizerStateCancelled:
        {
            // 判断
            if (ABS(angle) > 0.5) {
                
                [self dismissViewControllerAnimated:YES completion:nil];
                
            } else {
                
                [UIView animateWithDuration:0.5 animations:^{
                    self.view.transform = CGAffineTransformIdentity;
                }];
            }
        }
            break;
        default:
            break;
    }
}
- (void)setupButtons {
    for (UIButton *button in self.arrayButtons) {
        if (button.tag == 24) {
            [button addTarget:self action:@selector(pushLCTimingClosureVC) forControlEvents:(UIControlEventTouchUpInside)];
        }
    }
}
- (void)pushLCTimingClosureVC {
    NSString *clzName = @"LCTimingClosureViewController";
    Class clz = NSClassFromString(clzName);//将字符串转化成class
    LCViewController *viewController = [[clz alloc] init];
    viewController.vcInitDictData = @{@"back":@"dismiss"};
    LCNavigationController *navController = [[LCNavigationController alloc] initWithRootViewController:viewController];
    [self presentViewController:navController animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupButtons];
    [self setupPan];
    _ThemeMgr.mainColor = [UIColor whiteColor];
    [_playOrPauseButton setImage:_I(@"btn_play_normal") forState:(UIControlStateNormal)];
    [_playOrPauseButton setImage:_I(@"btn_pause_normal") forState:(UIControlStateSelected)];
    [_randomOrSinglePlayButton setImage:_I(@"new循环") forState:(UIControlStateNormal)];
//    _ThemeMgr.mainColor = [UIColor greenColor];
//    break;
//case 2:
//    _ThemeMgr.mainColor = [UIColor purpleColor];
//    break;
//case 3:
//    _ThemeMgr.mainColor = [UIColor redColor];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"alpha" object:self];
    [LCFloatingWindow sharedInstance].hidden = YES;
    LCSongLyricsTableViewController *songLyricsTableViewController = [[LCSongLyricsTableViewController alloc] initWithStyle:UITableViewStylePlain];
    _songLyricsTableViewController = songLyricsTableViewController;
    //添加以下代码关闭估算行高
    _songLyricsTableViewController.tableView.estimatedRowHeight = 0;
    _songLyricsTableViewController.tableView.estimatedSectionHeaderHeight = 0;
    _songLyricsTableViewController.tableView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:songLyricsTableViewController.tableView];
    
    [songLyricsTableViewController.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.albumLabel.mas_bottom).offset(30);
        make.bottom.equalTo(self.progressSlider.mas_top).offset(-30);
    }]; //添加歌词tableView

    //切换随机播放
    [self randomOrSinglePlay:_randomOrSinglePlayButton showHUD:NO];
    // 初始化界面
    [self refreshUIWithStatus:_LCPlayer.kstatus];
    [self refreshUIWithSong:_LCPlayer.playingSong];
    [self refreshUIWithCurrentTime:_LCPlayer.currentTime totalTime:_LCPlayer.totalTime];
    
    // 安装通知
    [self setupNotifications];
    
    // 界面初始化
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"slider-block"] forState:UIControlStateNormal];
    self.progressSlider.minimumTrackTintColor = [_ThemeMgr mainColor];//[UIColor colorWithRed:232/255.0 green:45/255.0 blue:51/255.0 alpha:1]
    self.progressSlider.maximumTrackTintColor = [UIColor clearColor];
//    生成透明图片
    CGSize s=CGSizeMake(1, 1);
    UIGraphicsBeginImageContextWithOptions(s, 0, [UIScreen mainScreen].scale);
    UIRectFill(CGRectMake(0, 0, 1, 1));
    UIImage *img=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
//    添加图片，大按钮就去掉了，这个img置为空是去不掉的
    [self.bufferProgressSlider setThumbImage:img forState:UIControlStateNormal];
    self.bufferProgressSlider.minimumTrackTintColor = [UIColor darkGrayColor];
    self.bufferProgressSlider.maximumTrackTintColor = [UIColor whiteColor];
    
    [self.progressSlider addTarget:self action:@selector(handleTouchUp:) forControlEvents:UIControlEventTouchUpInside];
    [self.progressSlider addTarget:self action:@selector(handleTouch:) forControlEvents:UIControlEventAllTouchEvents];

    // 设置约束
}

#pragma mark - 通知处理 -
// 安装通知
- (void)setupNotifications {
    // 1. 安装播放状态发生变化的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerStatusDidChangedNotification:) name:LCMusicPlayerStatusDidChangedNotification object:_LCPlayer];
    
    // 2. 安装播放歌曲发生变化的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerPlayingSongDidChangedNotification:) name:LCMusicPlayerPlayingSongDidChangedNotification object:_LCPlayer];
    
    // 3. 安装歌曲进度发生变化后回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerCurrentTimeDidChangedNotification:) name:LCMusicPlayerCurrentTimeDidChangedNotification object:_LCPlayer];
    // 4. 缓冲进度发生变化后回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bufferProgressDidChangedNotification:) name:LCBufferProgressDidChangedNotification object:_LCPlayer];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ClickSpecificSearchNotification:) name:@"ClickSpecificSearch" object:nil];

}
// 卸载通知
- (void)teardownNotifications {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
//关闭
- (IBAction)clickCloseButtonAction:(UIButton *)sender {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"alpha" object:self];
    [self dismissViewControllerAnimated:YES completion:nil];

}
#pragma mark - 歌谱的点击事件
- (IBAction)lyricBooksClick:(id)sender {
    NSLog(@"歌谱的点击事件");
    LSZLyricBookModel * model = [[LSZLyricBookModel alloc]init];
    NSArray * arrayExisting = [WHCSqlite query:[model class]];
    NSString * string = @"0";
    NSString * imageStr = @"";
    NSString * urlStr = @"";
    for ( LSZLyricBookModel * mg in arrayExisting) {
        if ([mg.id_id isEqualToString:self.id_id]) {
            string = @"1";
            imageStr = [NSString stringWithFormat:@"%@",mg.img];
            urlStr = NSStr(mg.url);
            break;
        }
    }
    if ([string isEqualToString:@"1"]) {
        LSZALyricBooksViewController * vc = [[LSZALyricBooksViewController alloc]init];
        vc.imageViewString = imageStr;
        vc.titleStr = self.titleLabel.text;
        vc.urlString = urlStr;
        [self presentViewController:vc animated:YES completion:nil];
    }else{
        [self SearchLyricBooks];
    }
}
#pragma mark - 没存歌曲 选择
-(void)SearchLyricBooks
{
    __weak typeof(self) weakSelf = self;
    LSZLyricBooksPopup * VC = [[LSZLyricBooksPopup alloc]init];
    [VC show];
    [VC initWithKeyword:weakSelf.titleLabel.text];
}
#pragma mark - 通知处理回调
- (void)musicPlayerStatusDidChangedNotification:(NSNotification *)notification {
    // 获取当前播放状态
    LCMusicPlayerStatus kstatus = [notification.userInfo[kMusicPlayerStatus] integerValue];
    // 绑定播放状态和界面之间的关系
    [self refreshUIWithStatus:kstatus];
}

- (void)musicPlayerPlayingSongDidChangedNotification:(NSNotification *)notification {
    JKSongsMessStatus *playingSong = notification.userInfo[kMusicPlayerPlayingSong];
    [self refreshUIWithSong:playingSong];
}

- (void)musicPlayerCurrentTimeDidChangedNotification:(NSNotification *)notification {
    NSTimeInterval currentTime = [notification.userInfo[kCurrentTime] floatValue];
    NSTimeInterval totalTime = [notification.userInfo[kTotalTime] floatValue];
    if (_songLyricsTableViewController.isDragging == NO) {
        [self refreshUIWithCurrentTime:currentTime totalTime:totalTime];
    }
    
}
- (void)bufferProgressDidChangedNotification:(NSNotification *)notification {
    float bufferProgress = [notification.userInfo[kBufferProgress] floatValue];
    [UIView animateWithDuration: 0.3 animations: ^{
        [self.bufferProgressSlider setValue:bufferProgress animated:YES];
    } completion: nil];
    
}
-(void)ClickSpecificSearchNotification:(NSNotification *)notification
{
    NSDictionary * dic =  [[NSDictionary alloc]initWithDictionary:notification.userInfo];
    NSLog(@"%@......",dic);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格  和结束刷新
        LSZLyricBooksLyricsVC * VC = [[LSZLyricBooksLyricsVC alloc]init];
        VC.arrayManager = dic[@"array"];
        VC.curIndex = [dic[@"row"] integerValue];
        VC.id_id = self.id_id;
        [self presentViewController:VC animated:YES completion:nil];
    });
}
#pragma mark - UI刷新 -
// 通过歌曲对象刷新UI
- (void)refreshUIWithSong:(JKSongsMessStatus *)song {
    
    if (song.title == nil) {
        song = _LCPlayer.selectedJKSongsMessStatus;
    }
    
    // 设置背景
    self.backgroundImageView.image = [UIImage imageNamed:@"player_bg"];
    // 设置标题
    self.titleLabel.text = song.title;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.id_id = song.id;
    //设置专辑名字
    self.albumLabel.text = song.singerName;

    // 歌词面板更新
//    @try {
        [self lrcWordWithID:song];
//    } @catch (NSException *exception) {
//    }
}
//下载歌词
-(NSString *)downloadKlrcWithStr:(NSString *)fileStr newStr:(NSString *)newStr{
    NSString *filePath = [kNetworkTool lrcWithNewStr:newStr];
    [fileStr writeToFile:filePath atomically:YES  encoding:NSUTF8StringEncoding error:nil];
    return filePath;
}

- (void)lrcWordWithID:(JKSongsMessStatus *)song {
    
    NSString *sid = song.fileUrl;
    sid = [sid stringByReplacingOccurrencesOfString:@"http://" withString:@""];
    sid = [sid stringByReplacingOccurrencesOfString:@"/" withString:@""];

    NSLog(@" = %@", sid);
    if (sid == nil) {
        return;
    }//没有意义做网络判断
    
    if ([song.singerName isEqualToString:@"圣经新约"] || [song.singerName isEqualToString:@"圣经旧约"]) {
        NSString *str = [[TheHomeManager shareTheHomeManager] getShengJingLrc:[song.id integerValue]];
        [self getLrcArrayWithPath:[self downloadKlrcWithStr:str newStr:sid]];//获得歌词数组
        
    }else{
        sid = song.id;//临时
        NSLog(@"sid = %@", sid);
        NSDictionary *dict = [song yy_modelToJSONObject];
        NSLog(@"dict = %@", dict);
        if ([sid isEqualToString:@""] || sid == nil) {
            NSArray *arr3 = [song.fileUrl componentsSeparatedByString:@"/"];//临时
            sid = [arr3 lastObject];
            sid = [sid stringByReplacingOccurrencesOfString:@".mp3" withString:@""];
            sid = [sid stringByReplacingOccurrencesOfString:@".m4a" withString:@""];
        }
        @weakify(self)
        self.songLyricsTableViewController.lrcArray = nil;
        self.songLyricsTableViewController.lrc2Array = nil;//初始化值
        [self.songLyricsTableViewController.tableView reloadData];
        NSString *lrcPath = [kNetworkTool lrcWithNewStr:sid];//歌词路径
        if ([kNetworkTool isFileExist:lrcPath]) {//判断是否存在
            [self getLrcArrayWithPath:lrcPath];//赋予路径,读取歌词
        }
        if ([song.id integerValue] < 900000) {//老歌词
            NSDictionary * dicGC = @{@"type":@"search_geci_music", @"parentId":sid};
            [kNetworkTool POSTWithUrlString:@"http://api2015.9ku.com/ApiHandler.php?action=fuyin" parameters:dicGC success:^(id responseObject) {
                @strongify(self)

                NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
                
                if ([[json objectForKey:@"data"] isKindOfClass:[NSString class]]) {
                    if ([kNetworkTool isFileExist:lrcPath]) {//判断是否存在
                        //歌词没有的情况,判断网络是否有,有的话就重新下载一遍歌词
                        NSString *lrcData = json[@"data"];
                        if (self.songLyricsTableViewController.lrcArray.count == 0 && lrcData.length > 1) {
                            //否则下载歌词,读取歌词
                            [self getLrcArrayWithPath:[self downloadKlrcWithStr:json[@"data"] newStr:sid]];//获得歌词数组
                        }
                    }else{
                        //否则下载歌词,读取歌词
                        [self getLrcArrayWithPath:[self downloadKlrcWithStr:json[@"data"] newStr:sid]];//获得歌词数组
                    }
                }
            } failure:^(NSError *error) {   NSLog(@"error = %@", error);
            }];
        }else {//新歌词
            NSDictionary * dicGC =
            [NSDictionary dictionaryWithObjectsAndKeys:sid, @"id", nil];
            NSString *url =
            [NSString stringWithFormat:@"%@/Music/get_lrc",http_zongSJUrl];
            [kNetworkTool POSTFuYinWithUrlString:url input:dicGC success:^(NSDictionary *json) {
                @strongify(self)
                
                if ([[json objectForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
                    NSString *lrcData = json[@"data"][@"lrc"];
                    if ([lrcData isKindOfClass:[NSNull class]]) {
                        return ;
                    }
                    if (!([lrcData containsString:@"["] && [lrcData containsString:@"]"])) {
                        self.songLyricsTableViewController.lrc2Array = [lrcData componentsSeparatedByString:@"\n"];
                        [self.songLyricsTableViewController.tableView reloadData];
                        NSString *lrcTemp = [lrcData stringByReplacingOccurrencesOfString:@" " withString:@""];
                        if (lrcTemp.length < 11) {//假如歌词太少就不显示
                            self.songLyricsTableViewController.lrcArray = nil;
                            [self.songLyricsTableViewController.tableView reloadData];
                        }
                        return ;
                    }
                    if ([kNetworkTool isFileExist:lrcPath]) {//判断是否存在
                        //歌词没有的情况,判断网络是否有,有的话就重新下载一遍歌词
                        if (self.songLyricsTableViewController.lrcArray.count == 0 && lrcData.length > 1) {
                            //否则下载歌词,读取歌词
                            [self getLrcArrayWithPath:[self downloadKlrcWithStr:json[@"data"][@"lrc"] newStr:sid]];//获得歌词数组
                        }
                    }else{
                        //否则下载歌词,读取歌词
                        [self getLrcArrayWithPath:[self downloadKlrcWithStr:json[@"data"][@"lrc"] newStr:sid]];//获得歌词数组
                    }
                    
                }
            } failure:^(NSError *error) {
                NSLog(@"error = %@", error);
            }];
        }
    }
}
// 播放状态和界面之间的关系
- (void)refreshUIWithStatus:(LCMusicPlayerStatus)status {
    // 告诉播放按钮状态和播放器内部的状态之间的关系
    self.playOrPauseButton.selected = status == LCMusicPlayerStatusPlaying;
    NSLog(@"self.playOrPauseButton.selected = %d", self.playOrPauseButton.selected);
}
// 通过播放的当前时间和总共时间刷新UI
- (void)refreshUIWithCurrentTime:(float)currentTime totalTime:(float)totalTime {
        // 更新UI
    self.currentTimeLabel.text = [self getdateWithStrTime:currentTime];
    self.totalTimeLabel.text = [self getdateWithStrTime:totalTime];
    
    self.progressSlider.value = currentTime / totalTime;
    @try {
        [self playControlLrcWithCurrentTime:currentTime totalTime:totalTime];
    } @catch (NSException *exception) {
    }
}
-(NSString *)getdateWithStrTime:(float)strTime{
    NSInteger fen = (NSInteger)strTime/60;
    NSInteger miao = (NSInteger)strTime %60/1;
    NSString * timeStr = @"00:00";
    if (fen<10) {
        if (miao<10) {
            timeStr = [NSString stringWithFormat:@"0%zd:0%zd", fen,miao];
        }else
            timeStr = [NSString stringWithFormat:@"0%zd:%zd", fen,miao];
    }else{
        if (miao<10) {
            timeStr = [NSString stringWithFormat:@"%zd:0%zd", fen,miao];
        }else
            timeStr  = [NSString stringWithFormat:@"%zd:%zd", fen,miao];
    }

    return timeStr;
}

#pragma mark -- Help Methods

//获得歌词数组
- (void)getLrcArrayWithPath:(NSString *)path{
    LCLrcAnalyzer *  analyzer = [[LCLrcAnalyzer alloc] init];
    _songLyricsTableViewController.lrcArray =  [analyzer analyzerLrcBylrcString:[NSString  stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]];
    
}
#pragma mark - 歌词控制 监测播放进度
- (void)playControlLrcWithCurrentTime:(float)currentTime totalTime:(float)totalTime{

        if (!_songLyricsTableViewController.isDragging) {

            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                      //歌词滚动显示
                    for ( int i = (int)(_songLyricsTableViewController.lrcArray.count - 1); i >= 0 ;i--) {
                        LCLrcLine * lrc = _songLyricsTableViewController.lrcArray[i];
                        if (lrc.time < currentTime) {
                            if (_songLyricsTableViewController.lrcArray.count > _songLyricsTableViewController.currentRow) {
                                _songLyricsTableViewController.currentRow = i;
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [UIView animateWithDuration: 0.5 animations: ^{
                                        [_songLyricsTableViewController.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow: _songLyricsTableViewController.currentRow inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];

                                    } completion: nil];
                                    [_songLyricsTableViewController.tableView reloadData];
                                });
                                break;
                            }
                        }
                    }
            });
        }

    
}

#pragma mark - UIScrollViewDelegate -
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 目标 -> 改变封面的alpha
    // 计算滚动比例
//    float rate = scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width;
//    
//    // 通过滚动比例计算alpha值
//    self.coverImageView.alpha = 1.0 - rate;
}

#pragma mark - actions -
// 所有的动作操作关注点 -> 业务逻辑代码
- (IBAction)actionPlayOrPause:(id)sender {
    // 通过按钮的状态来触发播放状态
    if(_LCPlayer.kstatus == LCMusicPlayerStatusPlaying) {
        [_LCPlayer pause];
    } else {
        [_LCPlayer play];
    }
}

- (IBAction)actionPrev:(UIButton *)sender {
    [_LCPlayer prev];
    [self noQuickClick:sender];
    [self resetProgress];
}

- (IBAction)actionNext:(UIButton *)sender {
    [_LCPlayer next];
    [self noQuickClick:sender];
    [self resetProgress];
}
//屏蔽快速点击
- (void)noQuickClick:(UIButton *)sender {
    sender.userInteractionEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        sender.userInteractionEnabled = YES;
    });
}
//重置进度
-(void)resetProgress {
    self.totalTimeLabel.text = [LSZSpecialPackaging TimeStamp:_LCPlayer.playingSong.duration];//读取网站的歌曲时间
    _songLyricsTableViewController.currentRow = 0;
    self.bufferProgressSlider.value = 0;
    self.currentTimeLabel.text = @"00:00";
    self.progressSlider.value = 0;
    if (_songLyricsTableViewController.lrcArray.count > 0) {
        [_songLyricsTableViewController.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:NO];
        [_songLyricsTableViewController.tableView reloadData];
    }
}

#pragma mark - SliederAction

- (IBAction)actionChangeProgress:(UISlider *)sender {
    float percent = sender.value;
    float currentTime = percent * _LCPlayer.totalTime;
    NSDateFormatter *dateFmt = [NSDateFormatter new];
    dateFmt.dateFormat = @"mm:ss";
    self.currentTimeLabel.text = [dateFmt stringFromDate:[NSDate dateWithTimeIntervalSince1970:currentTime]];
}
- (void)handleTouch:(UISlider *)slider{
    _songLyricsTableViewController.isDragging = YES;
}
- (void)handleTouchUp:(UISlider *)slider{
    if (_LCPlayer.avPlayer.currentItem != nil) {
        @try {
            float sliderValue = slider.value * CMTimeGetSeconds(_LCPlayer.avPlayer.currentItem.duration);//* _LCPlayer.totalTime;
            [_LCPlayer.avPlayer seekToTime:CMTimeMake(sliderValue, 1)];

        } @catch (NSException *exception) {
            NSLog(@"exception = %@", exception);
        } @finally {
            
        }
        
        
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _songLyricsTableViewController.isDragging = NO;
    });

}
- (IBAction)clickRandomPlay:(UIButton *)sender {
    _LCPlayer.listStatus = (_LCPlayer.listStatus + 1) % 3;
    [self randomOrSinglePlay:sender showHUD:YES];
}
- (void)randomOrSinglePlay:(UIButton *)button showHUD:(BOOL)showHUD{
    if (_LCPlayer.listStatus == LCMusicListStatusAllCycle) {
        [button setImage:_I(@"new循环") forState:(UIControlStateNormal)];
//        [button setImage:[UIImage imageNamed:@"new循环"] forState:0];
        if (showHUD) {
            [self showHud1:@"循环播放"];
        }
    } else if(_LCPlayer.listStatus == LCMusicListStatusRandom){
        [button setImage:_I(@"new随机") forState:(UIControlStateNormal)];
//        [button setImage:[UIImage imageNamed:@"new随机"] forState:0];
        if (showHUD) {
            [self showHud1:@"随机播放"];
        }
    } else if(_LCPlayer.listStatus == LCMusicListStatusSingleCycle){
        [button setImage:_I(@"new单曲") forState:(UIControlStateNormal)];
//        [button setImage:[UIImage imageNamed:@"new单曲"] forState:0];
        if (showHUD) {
            [self showHud1:@"单曲循环"];
        }
    }
}

- (IBAction)showListsClick:(UIButton *)sender {
    [self example7];
}
- (void)example7 {
    zhWallView *wallView = [self wallView];
    wallView.didClickFooter = ^(zhWallView * _Nonnull sheetView) {
        [self.zh_popupController dismiss];
    };

    self.zh_popupController = [zhPopupController new];
    self.zh_popupController.layoutType = zhPopupLayoutTypeBottom;
    [self.zh_popupController presentContentView:wallView];
}
- (zhWallView *)wallView {
    CGRect rect = CGRectMake(100, 100, [UIScreen mainScreen].bounds.size.width, 300);
    zhWallView *wallView = [[zhWallView alloc] initWithFrame:rect];
    wallView.isPlayerVC = YES;
    wallView.wallHeaderLabel.text = [NSString stringWithFormat:@"清空"];
    wallView.wallFooterLabel.text = @"关闭";
    wallView.models = @[wallView.wallHeaderLabel.text, wallView.wallFooterLabel.text];
    [wallView autoAdjustFitHeight];
    return wallView;
}
- (IBAction)clickDownloadSong:(UIButton *)sender {
    [_LCPlayer downloadSong];
}


@end
